<template>
  <div class="room-management">
    <div class="header">
      <h2>房间管理</h2>
      <el-button type="primary" @click="showAddDialog">新增房间</el-button>
    </div>

    <el-table :data="paginatedRooms" style="width: 100%" v-loading="loading">
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="minimum_charge" label="最低消费">
        <template #default="scope">
          ¥{{ scope.row.minimum_charge }}
        </template>
      </el-table-column>
      <el-table-column prop="minimum_hours" label="低消时长">
        <template #default="scope">
          {{ scope.row.minimum_hours }}小时
        </template>
      </el-table-column>
      <el-table-column prop="overtime_rate" label="超时费/小时">
        <template #default="scope">
          ¥{{ scope.row.overtime_rate }}/小时
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button-group>
            <el-button size="small" @click="showEditDialog(scope.row)">
              编辑
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="rooms.length"
        :page-sizes="[15, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogType === 'add' ? '新增房间' : '编辑房间'"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form 
        :model="form" 
        :rules="rules" 
        ref="roomForm" 
        label-width="100px"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="最低消费" prop="minimum_charge">
          <el-input-number 
            v-model="form.minimum_charge" 
            :min="0" 
            :precision="2" 
          />
        </el-form-item>
        <el-form-item label="低消时长" prop="minimum_hours">
          <el-input-number 
            v-model="form.minimum_hours" 
            :min="0" 
            :precision="1" 
          />
        </el-form-item>
        <el-form-item label="超时费/小时" prop="overtime_rate">
          <el-input-number 
            v-model="form.overtime_rate" 
            :min="0" 
            :precision="2" 
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="空闲" value="空闲" />
            <el-option label="使用中" value="使用中" />
            <el-option label="维护中" value="维护中" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { roomAPI } from '../api/services'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'RoomManagement',
  setup() {
    const rooms = ref([])
    const loading = ref(false)
    const dialogVisible = ref(false)
    const dialogType = ref('add')
    const roomForm = ref(null)
    const currentId = ref(null)
    const currentPage = ref(1)
    const pageSize = ref(15)

    const form = ref({
      name: '',
      minimum_charge: 0,
      minimum_hours: 0,
      overtime_rate: 0,
      status: '空闲'
    })

    const rules = {
      name: [
        { required: true, message: '请输入房间名称', trigger: 'blur' },
        { min: 2, message: '名称长度至少为2个字符', trigger: 'blur' }
      ],
      minimum_charge: [
        { required: true, message: '请输入最低消费', trigger: 'blur' }
      ],
      minimum_hours: [
        { required: true, message: '请输入低消时长', trigger: 'blur' }
      ],
      overtime_rate: [
        { required: true, message: '请输入超时费率', trigger: 'blur' }
      ]
    }

    // 添加分页计算属性
    const paginatedRooms = computed(() => {
      const startIndex = (currentPage.value - 1) * pageSize.value
      const endIndex = startIndex + pageSize.value
      return rooms.value.slice(startIndex, endIndex)
    })

    const getStatusType = (status) => {
      const types = {
        '空闲': 'success',
        '使用中': 'warning',
        '维护中': 'danger'
      }
      return types[status] || 'info'
    }

    const fetchRooms = async () => {
      loading.value = true
      try {
        const response = await roomAPI.getRooms()
        console.log('Rooms response:', response)
        rooms.value = response
      } catch (error) {
        console.error('Failed to fetch rooms:', error)
        console.error('Error details:', error.response || error)
        ElMessage.error('获取房间信息失败')
      } finally {
        loading.value = false
      }
    }

    const resetForm = () => {
      form.value = {
        name: '',
        minimum_charge: 0,
        minimum_hours: 0,
        overtime_rate: 0,
        status: '空闲'
      }
      if (roomForm.value) {
        roomForm.value.resetFields()
      }
    }

    const showAddDialog = () => {
      dialogType.value = 'add'
      resetForm()
      dialogVisible.value = true
    }

    const showEditDialog = (row) => {
      dialogType.value = 'edit'
      currentId.value = row.id
      form.value = { ...row }
      dialogVisible.value = true
    }

    const handleSubmit = async () => {
      if (!roomForm.value) return
      try {
        await roomForm.value.validate()
        if (dialogType.value === 'add') {
          const response = await roomAPI.createRoom(form.value)
          if (response.message === '创建成功') {
            ElMessage.success('创建成功')
          }
        } else {
          await roomAPI.updateRoom(currentId.value, form.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchRooms()
      } catch (error) {
        console.error('Failed to submit room:', error)
        ElMessage.error(error.response?.data?.detail || '操作失败')
      }
    }

    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除该房间吗？', '提示', {
          type: 'warning'
        })
        
        await roomAPI.deleteRoom(row.id)
        
        ElMessage.success('删除成功')
        fetchRooms()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('Failed to delete room:', error)
          ElMessage.error('删除失败')
        }
      }
    }

    // 添加分页处理方法
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1  // 重置到第一页
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
    }

    onMounted(() => {
      fetchRooms()
    })

    return {
      rooms,
      loading,
      dialogVisible,
      dialogType,
      form,
      rules,
      roomForm,
      getStatusType,
      showAddDialog,
      showEditDialog,
      handleSubmit,
      handleDelete,
      currentPage,
      pageSize,
      paginatedRooms,
      handleSizeChange,
      handleCurrentChange,
    }
  }
}
</script>

<style scoped>
.room-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 